/**
 * JFunny - A funny programming language
 * Copyright (C) 2013  fanguangping
 * Any problem email me: fguangping@gmail.com
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 3
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 **/
package org.jfunny.core.parser;

import java.io.PushbackReader;
import java.io.StringReader;
import java.util.NoSuchElementException;

import org.jfunny.core.ds.Arg;
import org.jfunny.core.ds.Statement;
import org.jfunny.core.ds.Symbol;

/**
 * 解析泛语言源代码语法的类
 * 
 * @author fanguangping
 *
 */
public class ParserFunny {
	public ParserFunny(ScannerFunny scanner) {
		this.scanner = scanner;
	}

	public static Statement parse(String funny) {
		String statement = null;
		if (funny != null && !funny.startsWith("{")) {
			statement = "{" + funny + "}";
		}
		else {
			statement = funny;
		}

		ParserFunny parser = new ParserFunny(new ScannerFunny(new PushbackReader(new StringReader(statement))));
		try {
			return parser.next();
		}
		catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public boolean hasNext() throws Exception {
		return scanner.hasNext();
	}

	public Statement next() throws Exception {
		return parseStatement(scanner.next());
	}

	private Statement parseStatement(Object token) throws Exception {
		Statement root = new Arg();

		if (Token.PAREN_L.equals(token)) {
			Object nextToken = nextToken();
			while (!Token.PAREN_R.equals(nextToken)) {
				Statement s = parseExpression(nextToken);
				root.addChild(s);

				nextToken = nextToken();
			}
		}

		return root;
	}

	private Statement parseExpression(Object token) throws Exception {
		if (token instanceof Symbol) {
			return (Statement) token;
		}
		else {
			return parseStatement(token);
		}
	}

	private Object nextToken() throws Exception {
		if (!scanner.hasNext())
			throw new NoSuchElementException("Unexpected end of Object stream.");
		return scanner.next();
	}

	private ScannerFunny scanner;
}
